package service

import (
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/honwee/awm/internal/model"
	"github.com/honwee/awm/internal/repository"
)

var (
	ErrInvalidAPIKey = errors.New("invalid API key")
)

type ProjectUserService struct {
	projectUserRepo *repository.ProjectUserRepository
}

func NewProjectUserService(projectUserRepo *repository.ProjectUserRepository) *ProjectUserService {
	return &ProjectUserService{
		projectUserRepo: projectUserRepo,
	}
}

// ValidateAPIKey 验证API Key并返回项目用户信息
func (s *ProjectUserService) ValidateAPIKey(apiKey string) (*model.ProjectUser, error) {
	if apiKey == "" {
		return nil, ErrInvalidAPIKey
	}
	return s.projectUserRepo.FindByAPIKey(apiKey)
}

// GenerateAPIKey 生成新的API Key
func (s *ProjectUserService) GenerateAPIKey(projectID uint64, userID string) (string, error) {
	// 验证项目用户关系是否存在
	exists, err := s.projectUserRepo.ValidateProjectUser(projectID, userID)
	if err != nil {
		return "", err
	}
	if !exists {
		return "", errors.New("project user relationship not found")
	}

	// 生成新的API Key
	apiKey := uuid.New().String()

	// 更新API Key
	err = s.projectUserRepo.UpdateAPIKey(projectID, userID, apiKey)
	if err != nil {
		return "", err
	}

	return apiKey, nil
}

// DeleteAPIKey 删除API Key
func (s *ProjectUserService) DeleteAPIKey(projectID uint64, userID string) error {
	// 检查项目用户是否存在
	projectUser, err := s.projectUserRepo.FindByProjectIDAndUserID(projectID, userID)
	if err != nil {
		return fmt.Errorf("failed to find project user: %w", err)
	}
	if projectUser == nil {
		return fmt.Errorf("project user not found")
	}

	// 清除API Key
	projectUser.APIKey = ""

	// 更新记录
	err = s.projectUserRepo.Update(projectUser)
	if err != nil {
		return fmt.Errorf("failed to update project user: %w", err)
	}

	return nil
}

// CreateProjectUser 创建项目用户关系
func (s *ProjectUserService) CreateProjectUser(projectID uint64, userID string, role int8) error {
	// 检查项目用户关系是否已存在
	exists, err := s.projectUserRepo.ValidateProjectUser(projectID, userID)
	if err != nil {
		return fmt.Errorf("failed to validate project user: %w", err)
	}
	if exists {
		return fmt.Errorf("project user relationship already exists")
	}

	// 创建新的项目用户关系
	projectUser := &model.ProjectUser{
		ProjectID: projectID,
		UserID:    userID,
		Role:      role,
	}

	return s.projectUserRepo.CreateProjectUser(projectUser)
}
